import React, { Component } from 'react'
import {login,regis} from './api/index'
export default class Login extends Component {
    state={
        name:'',
        pwd:"",
        flag:false,
        msg:""
    }
    render() {
        let {name,pwd,msg,flag}=this.state
        return (
            <div>
                <div><input type="text" placeholder="请输入姓名" name="name" value={name} onChange={this.changevalue}/></div>
                <div><input type="password" placeholder="请输入内容" name="pwd" value ={pwd} onChange={this.changevalue}/></div>
                <button onClick={()=>this.regiss(name,pwd)}>注册</button>
                <button onClick={()=>this.logins(name,pwd)}>登录</button>
                {
                    flag?<div style={{position:"fixed",height:"100%",color:"red"}}>{msg}</div>:''
                }
            </div>
        )
    }
    changevalue=(e)=>{
        this.setState({
            [e.target.name]:e.target.value
        })
    }
    regiss=async (name,pwd)=>{
        let res=await regis({name,pwd})
        if(res.data.code===1){
            this.props.history.push('./index')
        }else if(res.data.code===0){
            this.hint(res.data.msg)
        }else{
            this.hint(res.data.msg)
        }
    }
    logins=async (name,pwd)=>{
        if(name.trim()&&pwd.trim()){
            let res=await login({name:name.trim(),pwd:pwd.trim()})
            if(res.data.code===1){
                this.props.history.push('./index')
            }else if(res.data.code===0){
                this.hint(res.data.msg)
            }
        }else{
            this.hint("不能为空")
        }
    }
    hint=(msg)=>{
        this.setState({msg,flag:true})
            setTimeout(()=>{
                this.setState({flag:false})
            },2000)
    }
}
